package com.evaluity;

import org.json.JSONObject;

import com.evaluity.Usuario.OnLoginUsuario;

import android.os.Bundle;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Login extends Activity {

    
    private Button btnLogin;
    private EditText inputEmail;
    private EditText inputPassword;
    private TextView loginErrorMsg;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        inputEmail = (EditText) findViewById(R.id.txtEmail);
        inputEmail.setText(getEmail(this));
        inputPassword = (EditText) findViewById(R.id.txtPass);
        inputPassword.setVisibility(View.GONE);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        loginErrorMsg = (TextView) findViewById(R.id.login_error);
        
        btnLogin.setOnClickListener(new View.OnClickListener() {
 
            public void onClick(View view) {
                String email = inputEmail.getText().toString();
                String password = inputPassword.getText().toString();
                
                Usuario usuario = new Usuario();
                
                usuario.setOnLoginUsuario(new OnLoginUsuario() {
                	
                	@Override
                	public void onLoginWrong(String msg) {loginErrorMsg.setText(msg);}
                	
                	@Override
                	public void onUserExistDisplayPassField() {inputPassword.setVisibility(View.VISIBLE);}
                	
                	@Override
                	public void onLoginCorrect(JSONObject json, String msg) {
                		loginErrorMsg.setText("");
                		Intent itemintent = new Intent(Login.this, CentralActivity.class);
                		Login.this.startActivity(itemintent);
                	}
                });                
                usuario.login(Login.this, email, password);
            }
        });
        
    }
    
    //Get account mail----
    
    static String getEmail(Context context) {
	    AccountManager accountManager = AccountManager.get(context); 
	    Account account = getAccount(accountManager);

	    if (account == null) {
	      return null;
	    } else {
	      return account.name;
	    }
    }

    private static Account getAccount(AccountManager accountManager) {
	    Account[] accounts = accountManager.getAccountsByType("com.google");
	    Account account;
	    if (accounts.length > 0) {
	      account = accounts[0];      
	    } else {
	      account = null;
	    }
	    return account;
    }
    
    //Fi get account mail----
 
}